#include "common.h"
#include "search.h"

#include "../gui/mainwindow.h"
#include "../mapobjects/objectstorage.h"

Search search;

void Init ( MainWindow * window )
{
	search.init ( window );
}

Search::Search ()
: viewer ( NULL )
, storage ( NULL )
, searchDlg ( NULL )
{}

Search::~Search ()
{
	if ( NULL != searchDlg )
	{
		delete searchDlg;
	}
}

void Search::init ( MainWindow * wnd )
{
	this -> viewer = wnd -> getViewer ();

	searchDlg = new SearchDialog ( viewer );

	connect ( searchDlg, SIGNAL ( wantToFind ( QString & )), this, SLOT ( wantToFind ( QString & )));

	connect ( viewer, SIGNAL ( mapLoaded ()), this, SLOT ( onMapLoaded ()));
	connect ( wnd, SIGNAL ( searchToolSelected ()), this, SLOT ( onSearchToolSelected ()));
}

void Search::onSearchToolSelected ()
{
	if ( NULL != storage )
		searchDlg -> show ();
}

void Search::onMapLoaded ()
{
	this -> storage = viewer -> getStorage ();
	index.makeDict ( storage );
}

void Search::wantToFind ( QString & str )
{
	std::string stdStr ( str.toAscii ());
	vector<MapObject *> results;
	index.getObjectListByString ( stdStr, results );
	searchDlg -> displaySearchResults ( results );
}
